package com.expert.util;

import com.expert.vo.MenuVo;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: MenuTreeUtil
 * @Author: cxs
 * @Date: 2024/03/05 13:33
 * @Description:
 **/
public class MenuTreeUtil {
    public static List<MenuVo> buildDeptTreeByStream(List<MenuVo> trees){
        //获取parentId = 0的根节点
        List<MenuVo> list = trees.stream().filter(item -> item.getPid() == 0L).collect(Collectors.toList());
        //根据parentId进行分组
        Map<Long, List<MenuVo>> map = trees.stream().collect(Collectors.groupingBy(MenuVo::getPid));
        recursionFnTree(list, map);
        return list;
    }

    /**
     * 递归遍历节点
     * @param list
     * @param map
     */
    private static   void recursionFnTree(List<MenuVo> list, Map<Long, List<MenuVo>> map) {
        for (MenuVo treeSelect : list) {
            List<MenuVo> childList = map.get(treeSelect.getId());
            treeSelect.setChildItem(childList);
            if (null != childList && 0 < childList.size()) {
                recursionFnTree(childList, map);
            }
        }
    }
}
